<template>
  <div class="chart-container" ref="chartRef"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from "vue";
import * as echarts from "echarts";
import { defineProps } from "vue";

// 1. 定义父组件传递的 props
const props = defineProps({
  data: {
    type: Object,
    default: () => {
      return {
        dataX: ["A", "B", "C", "D", "E", "F"],
        dataY: [0, 0, 0, 0, 0, 0],
      };
    },
  },
});

const chartRef = ref(null);
let chartInstance = null;

// 2. 封装初始化图表的函数（复用）
const initChart = (datas) => {
  if (chartInstance) chartInstance.dispose(); // 销毁旧实例
  chartInstance = echarts.init(chartRef.value);

  const option = {
    tooltip: {
      show: true,
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    grid: {
      top: "8%",
      left: "2%",
      right: "2%",
      bottom: "10%",
      containLabel: true,
    },
    legend: {
      show: false,
      left: "0%",
      top: "2%",
    },
    xAxis: {
      boundaryGap: true,
      data: props.data.dataX,
      axisLine: {
        lineStyle: {
          color: "#E6EBF1",
          fontSize: 14,
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: "#8C8C8C",
      },
    },
    yAxis: {
      name: "",
      type: "value",
      inverse: false,
      minInterval:1,
      splitLine: {
        show: true,
        lineStyle: {
          color: "#E6EBF1",
        },
      },
      axisLabel: {
        textStyle: {
          color: "#8C8C8C",
          fontSize: 14,
        },
      },
      axisTick: {
        show: false,
      },
    },
    series: [
      {
        name: "2025",
        type: "bar",
        symbolSize: 7,
        smooth: true,
        itemStyle: {
          color: "#2776FF",
        },
        data: props.data.dataY,
      },
    ],
  };
  chartInstance.setOption(option);
};

onMounted(() => {
  initChart(); // 组件挂载时初始化

  // 响应式resize
  const handleResize = () => chartInstance && chartInstance.resize();
  window.addEventListener("resize", handleResize);
  onUnmounted(() => {
    window.removeEventListener("resize", handleResize);
    chartInstance && chartInstance.dispose();
  });
});

watch(
  () => props.data,
  () => initChart()
);
</script>

<style scoped>
.chart-container {
  width: 100%; /* 自适应父容器宽度 */
  height: 100%;
}
</style>
